package com.cloudm.technician.ui.modules.common.register

import android.content.Intent
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import com.cloudm.technician.R
import com.cloudm.technician.data.config.Config
import com.cloudm.technician.extensions.openActivity
import com.cloudm.technician.extensions.string
import com.cloudm.technician.extensions.toast
import com.cloudm.technician.ui.base.BaseFragment
import com.cloudm.technician.ui.modules.common.home.HomeActivity
import com.cloudm.technician.ui.modules.web.WebActivity
import kotlinx.android.synthetic.main.fragment_register.*

/**
 * 作者: wesley
 * 时间: 2017/12/14
 * 描述: ui
 */
class RegisterFragment : BaseFragment<RegisterPresenter>(), RegisterContract.View {

    private var flag: Int = 0
    var listener: OnTitleReceiveListener? = null

    companion object {
        private const val FLAG = "FLAG"
        fun newInstance(flag: Int) = RegisterFragment().apply {
            arguments = Bundle().apply {
                putInt(FLAG, flag)
            }
        }
    }

    override val resource: Int
        get() = R.layout.fragment_register

    override fun initInject() {
        DaggerRegisterComponent.builder().appComponent(appComponent).registerPresenterModule(
                RegisterPresenterModule(this)).build().inject(this)
    }

    override fun handleBundle(bundle: Bundle) {
        flag = bundle.getInt(FLAG)
    }

    override fun initVariables() {

    }

    override fun initViews(view: View) {
        presenter?.buildViewByFlag(flag)
    }

    override fun initListener() {
        etPhoneNumber.addTextChangedListener(TextWatchListener(0))
        etPassword.addTextChangedListener(TextWatchListener(1))
        etPasswordConfirm.addTextChangedListener(TextWatchListener(2))
        etPhoneNumber.onFocusChangeListener = FocusChangeListener(0)
        etPassword.onFocusChangeListener = FocusChangeListener(1)
        etPasswordConfirm.onFocusChangeListener = FocusChangeListener(2)
        llClearPhoneNumber.setOnClickListener(OnceClickListener())
        llClearPassword.setOnClickListener(OnceClickListener())
        llClearPasswordConfirm.setOnClickListener(OnceClickListener())
        btnVerificationCode.setOnClickListener(OnceClickListener())
        btnSubmit.setOnClickListener(OnceClickListener())
        tvServiceContract.setOnClickListener(OnceClickListener())
    }


    interface OnTitleReceiveListener {
        fun onTitleReceive(title: String?)
    }


    override fun buildTitleRegister() {
        listener?.onTitleReceive(mContext.resources.getString(R.string.register))
    }

    override fun buildTitleFindPassword() {
        listener?.onTitleReceive(mContext.resources.getString(R.string.find_password))
    }

    override fun setServiceAgreementVisible() {
        llRegisterContract.visibility = View.VISIBLE
    }

    override fun setServiceAgreementGone() {
        llRegisterContract.visibility = View.GONE
    }

    override fun getPhoneNumber(): String? = etPhoneNumber.string()

    override fun getVerificationCode(): String? = etVerificationCode.string()

    override fun getPassword(): String? = etPassword.string()

    override fun getPasswordConfirm(): String? = etPasswordConfirm.string()


    override fun getVerificationCode(phoneNumber: String?, flag: Int) {
        presenter?.getVerificationCode(phoneNumber, flag)
    }

    override fun verificationCodeLoadSuccess(verification: String) {
        mContext.toast(verification)
    }

    override fun verificationCodeLoadFailure(errorMsg: String) {
        mContext.toast(errorMsg)
    }

    override fun showInputPhoneNumberMsg() {
        mContext.toast(mContext.resources.getString(R.string.please_input_phone_number))
    }

    override fun showPhoneNumberFormatMsg() {
        mContext.toast(mContext.resources.getString(R.string.phone_number_format_is_error))
    }

    override fun showVerificationCodeEmptyMsg() {
        mContext.toast(mContext.resources.getString(R.string.please_input_verification_code))
    }

    override fun showPasswordEmptyMsg() {
        mContext.toast(mContext.resources.getString(R.string.please_input_password))
    }

    override fun showPasswordLengthMsg() {
        mContext.toast(mContext.resources.getString(R.string.password_length_lower_six))
    }

    override fun showPasswordNotSameMsg() {
        mContext.toast(mContext.resources.getString(R.string.password_not_same))
    }

    override fun showRegisterDialog() {
        showLoadingDialog(mContext.resources.getString(R.string.registering))
    }

    override fun showFindPasswordDialog() {
        showLoadingDialog(mContext.resources.getString(R.string.fing_passwording))
    }

    override fun hideDialog() {
        hideLoadingDialog()
    }

    override fun showErrorMsg(msg: String) {
        mContext.toast(msg)
    }

    override fun showUserEmptyMsg() {
        mContext.toast(mContext.resources.getString(R.string.no_user_msg))
    }

    override fun registerOrFindPasswordSuccess() {
        sendBroadcast()
        mContext.openActivity(HomeActivity::class.java)
    }

    override fun setBtnVericationEnabled() {
        btnVerificationCode.isEnabled = true
        btnVerificationCode.text = mContext.resources.getString(R.string.get_verification_code)
        btnVerificationCode.setBackgroundResource(R.drawable.drawable_button)
        btnVerificationCode.setTextColor(
                ContextCompat.getColor(mContext, R.color.common_color_ffffff))
    }

    override fun setBtnVericationNotEnabled(time: Long) {
        btnVerificationCode.isEnabled = false
        btnVerificationCode.text = mContext.resources.getString(R.string.resend_time, time)
        btnVerificationCode.setBackgroundResource(R.drawable.drawable_button_alpha)
        btnVerificationCode.setTextColor(
                ContextCompat.getColor(mContext, R.color.common_color_ffffff))
    }


    override fun registerOrFindPassword() {
        presenter?.registerOrFindPassword(getPhoneNumber(), getVerificationCode(), getPassword(),
                getPasswordConfirm(), flag)
    }

    override fun clearPhoneNumberVisible() {
        llClearPhoneNumber.visibility = View.VISIBLE
    }

    override fun clearPhoneNumberInvisible() {
        llClearPhoneNumber.visibility = View.INVISIBLE
    }

    override fun clearPasswordInVisible() {
        llClearPassword.visibility = View.INVISIBLE
    }

    override fun clearPasswordVisible() {
        llClearPassword.visibility = View.VISIBLE
    }

    override fun clearPasswordConfirmVisible() {
        llClearPasswordConfirm.visibility = View.VISIBLE
    }

    override fun clearPasswordConfirmInVisible() {
        llClearPasswordConfirm.visibility = View.INVISIBLE
    }

    override fun openWebActivity() {
        val intent = Intent(mContext, WebActivity::class.java).apply {
            putExtras(Bundle().apply {
                putString("url", Config.registerContractUrl)
            })
        }
        mContext.openActivity(intent, false)
    }

    inner class TextWatchListener(private val type: Int) : TextWatcher {

        override fun afterTextChanged(s: Editable?) {

        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            presenter?.updateIvClearStatus(type, s)
        }
    }

    //监听焦点
    inner class FocusChangeListener(private val flag: Int) : View.OnFocusChangeListener {

        override fun onFocusChange(view: View?, hasFocus: Boolean) {
            presenter?.updateIvClearStatus(hasFocus, flag)
        }
    }

    //点击事件
    inner class OnceClickListener : com.cloudm.technician.ui.widget.OnceClickListener() {

        override fun onOnceClick(view: View) {
            when (view.id) {
                R.id.llClearPhoneNumber -> etPhoneNumber.setText("")
                R.id.llClearPassword -> etPassword.setText("")
                R.id.llClearPasswordConfirm -> etPasswordConfirm.setText("")
                R.id.btnVerificationCode -> getVerificationCode(getPhoneNumber(), flag)
                R.id.btnSubmit -> registerOrFindPassword()
                R.id.tvServiceContract -> openWebActivity()
                else -> {
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        presenter?.cancelCountDown()
    }

    private fun sendBroadcast() {
        mContext.sendBroadcast(Intent().apply {
            action = Config.ACTION_LOGIN
        })
    }
}